<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024-03-12 09:44
 * +-------------------------------------------------------------
 */

namespace app\admin\controller;

use app\BaseController;
use OSS\Http\RequestCore_Exception;
use storage\Upload as UploadStorage;
use think\facade\Request;
use think\Response;

class Upload extends BaseController{
    private array $config;

    /**
     *  初始化配置信息
     * @return void
     */
    public function initialize(): void
    {
        // 存储配置信息alioss配置，建议后期存表lc_store_setting，区分那个商城用户上传或是管理后台上传
        $this->config = config('alioss');
    }

//    /**
//     * 获取上传配置信息
//     * @return Response
//     */
//    public function config(): Response
//    {
//        return Response::create($this->config);
//    }

    /**
     * 上传图片
     * @return Response
     */
    public function image(): Response
    {
        // 实例化上传类 阿里云OSS
        $storage = new UploadStorage($this->config);
        // 实例化上传类 本地local
        //        $storage = new UploadStorage();
        $storage->setUploadFile('file')
                ->setRootDirName('images')
                ->setValidationScene('image');
        if (!$storage->upload()) {
            return $this->error('图片上传失败：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();
        return $this->success('图片上传成功', $fileInfo);
    }

    /**
     * 上传视频
     * @return Response
     */
    public function video(): Response
    {
        $storage = new UploadStorage($this->config);
        $storage->setUploadFile('file')
                ->setRootDirName('videos')
                ->setValidationScene('video');
        if (!$storage->upload()) {
            return $this->error('视频上传失败：' . $storage->getError());
        }
        // 文件信息
        $fileInfo = $storage->getSaveFileInfo();
        return $this->success('视频上传成功', $fileInfo);
    }

    /**
     * 删除文件
     * @return Response $request
     * @throws RequestCore_Exception
     */
    public function delete(): Response
    {
        $filePath = Request::param('file_path','');
        if(!$filePath){
            return $this->error('路径不能为空');
        }
        $filePath = convert_left_slash($filePath);
        $storage = new UploadStorage($this->config);
        //        $storage = new UploadStorage();
        if (!$storage->delete($filePath)) {
            return $this->error('删除失败：' . $storage->getError());
        }
        return $this->success('删除成功');
    }
}